from django.shortcuts import render, redirect
from django import forms
from www import models
from utils.bootstrap_form import BootstrapForm
from utils.pager import Pagination


class LevelModelForm(BootstrapForm, forms.ModelForm):
    """ 级别表单（使用在添加与编辑中） """

    class Meta:
        model = models.Level
        fields = ["title", "percent"]


def level_list(request):
    """ 级别列表 """
    queryset = models.Level.objects.filter(active=1).all().order_by("percent")
    pager = Pagination(request, queryset)
    return render(request, "level_list.html", {"pager": pager})


def level_add(request):
    """ 新增级别 """
    if request.method == "GET":
        form = LevelModelForm()
        return render(request, "form2.html", {"form": form})

    form = LevelModelForm(data=request.POST)
    # 表单校验
    if not form.is_valid():
        return render(request, "form2.html", {"form": form})

    # 保存
    form.save()

    return redirect("level_list")


def level_edit(request, uid):
    """ 编辑级别 """
    instance = models.Level.objects.filter(active=1, id=uid).first()

    if request.method == "GET":
        form = LevelModelForm(instance=instance)
        return render(request, "form2.html", {"form": form})

    form = LevelModelForm(data=request.POST, instance=instance)
    # 表单校验
    if not form.is_valid():
        return render(request, "form2.html", {"form": form})

    # 保存
    form.save()

    # 获取上次url路径(注意：是从GET中.get)
    origin = request.GET.get("redirect")

    return redirect(origin)


def level_delete(request, uid):
    """ 删除级别 """
    # 获取上次url路径(注意：是从GET中.get)
    origin = request.GET.get("redirect")

    if request.method == "GET":
        return render(request, "delete.html", {"origin": origin})

    # 逻辑删除
    models.Level.objects.filter(active=1, id=uid).update(active=0)

    return redirect(origin)
